package com.smartrobot.smartrobot.activity;


import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.application.SmartRobotApplication;
import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMNotifier;
import com.easemob.chat.GroupChangeListener;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.easemob.util.NetUtils;
import com.huanxinapi.activity.BaseActivity;
import com.huanxinapi.activity.ChatAllHistoryFragment;
import com.huanxinapi.activity.CommonUtils;
import com.huanxinapi.activity.Constant;
import com.huanxinapi.activity.GroupsActivity;
import com.huanxinapi.activity.InviteMessage;
import com.huanxinapi.activity.InviteMessgeDao;
import com.huanxinapi.activity.User;
import com.huanxinapi.activity.UserDao;
import com.smartrobot.smartrobot.Config.Config;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.pagerHolder.InformationPagerHolder;
import com.smartrobot.smartrobot.pagerHolder.PersonalPagerHolder;
import com.smartrobot.smartrobot.pagerHolder.SocialCirlePagerHolder2;
import com.smartrobot.smartrobot.service.m_webscoketService;
import com.smartrobot.smartrobot.util.HomeKeyObserver;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.view.ToastCustom;
import com.smartrobot.smartrobot.websocket.Util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends BaseActivity{

    private ViewPager viewPager;
    private List<Fragment> holder;

    private RelativeLayout layoutInformation,layoutMessage,layoutSocial,layoutPersonal;
    private ImageView imageImformation,imageMessage,imageSocial,imagePersonal;
    private TextView pointImformation,pointMessage,pointSocial,pointPersonal;
//    private RadioGroup bottomMenu;

    private InformationPagerHolder informationPagerHolder;
//    private MessagePagerHolder messagePagerHolder;
    private ChatAllHistoryFragment chatHistoryFragment;
    private PersonalPagerHolder personalPagerHolder;
    private SocialCirlePagerHolder2 socialCirclePagerHolder;
    private Context context;
    private HomeKeyObserver mHomeKeyObserver;

    private boolean isStopFromSystem = false;
    static public MainActivity instance;

    private int currentPos = 0;

    //环信api
    // 账号在别处登录
    public boolean isConflict = false;
    //账号被移除
    boolean isCurrentAccountRemoved = false;
    boolean isAccountRemovedDialogShow;
    InviteMessgeDao inviteMessgeDao;
    UserDao userDao;
    NewMessageBroadcastReceiver msgReceiver;
    final String TAG = "环信 ------------》";
    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;




    private m_webscoketService.MyBinder myBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        //判断状态
        if(savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)){
            // 防止被移除后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            //在这帮助用户重新登录
//            SmartRobotApplication.getInstance().logout(null);
//            throw new NullPointerException();
            Log.e("==============>","调用了重启1");

        }else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
//            throw  new NullPointerException();
            Log.e("==============>","调用了重启2");

        }


        this.setContentView(R.layout.page_main1);

//        ToastCustom.showToast(getApplicationContext(), "登陆成功!1010");
        context = this.getApplicationContext();

        if(com.smartrobot.smartrobot.util.User.getInstance().getId().equals("未填写"))
            com.smartrobot.smartrobot.util.User.getUserInfo(getApplicationContext());

        init();
        initHuanXinAPI();
        initHomeKeyListener();


        LogToSd.log_init();
        Config.config_init(context);
        instance = this;

        Util.startWebsocketServer();
        m_webscoketService.init(context);
        startWebSocketService();

    }

    @Override
    protected void onStart() {


        super.onStart();
    }

    @Override
    protected void onRestart() {


        super.onRestart();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.e("========后退==========》","dfdf" + requestCode);

        SocialCirlePagerHolder2.changeFriendList( requestCode,  resultCode,  data);


    }

    void init(){

        viewPager = (ViewPager)findViewById(R.id.main_viewpager);
        viewPager.setOffscreenPageLimit(4);
        layoutInformation = (RelativeLayout)findViewById(R.id.main_menu_layout_information);
        layoutMessage = (RelativeLayout)findViewById(R.id.main_menu_layout_message);
        layoutSocial = (RelativeLayout)findViewById(R.id.main_menu_layout_social);
        layoutPersonal = (RelativeLayout)findViewById(R.id.main_menu_layout_personal);
        imageImformation = (ImageView)findViewById(R.id.main_imageview_imformation);
        imageMessage = (ImageView)findViewById(R.id.main_imageview_message);
        imageSocial = (ImageView)findViewById(R.id.main_imageview_social);
        imagePersonal = (ImageView)findViewById(R.id.main_imageview_personnal);
        pointImformation = (TextView)findViewById(R.id.unread_information);
        pointMessage = (TextView)findViewById(R.id.unread_message);
        pointSocial = (TextView)findViewById(R.id.unread_social);
        pointPersonal = (TextView)findViewById(R.id.unread_personal);


        layoutInformation.setOnClickListener(new onBottomListener());
        layoutMessage.setOnClickListener(new onBottomListener());
        layoutSocial.setOnClickListener(new onBottomListener());
        layoutPersonal.setOnClickListener(new onBottomListener());
        informationPagerHolder = new InformationPagerHolder();
        chatHistoryFragment  = new ChatAllHistoryFragment();
//        messagePagerHolder = new MessagePagerHolder();
        socialCirclePagerHolder = new SocialCirlePagerHolder2();
        personalPagerHolder = new PersonalPagerHolder();

        personalPagerHolder.setContext(getApplicationContext());



        holder = new ArrayList<Fragment>();
        holder.add(informationPagerHolder);
        holder.add(chatHistoryFragment);//改变
        holder.add(socialCirclePagerHolder);
        holder.add(personalPagerHolder);

        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(),holder);

        // 设置适配器
        viewPager.requestDisallowInterceptTouchEvent(true);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        imageImformation.setSelected(true);
//        informationPagerHolder.init();
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageSelected(int i) {

                imageImformation.setSelected(false);
                imageMessage.setSelected(false);
                imageSocial.setSelected(false);
                imagePersonal.setSelected(false);

                switch(i){
                    case 0:
                        currentPos = 0;
                        imageImformation.setSelected(true);
                        informationPagerHolder.init();
                        ((RadioButton)findViewById(R.id.main_information)).setChecked(true);
                        break;
                    case 1:
                        currentPos = 1;
                        imageMessage.setSelected(true);
                        ((RadioButton)findViewById(R.id.main_message)).setChecked(true);
                        chatHistoryFragment.init();

                        break;
                    case 2:

                        currentPos = 2;
                        imageSocial.setSelected(true);
                        ((RadioButton)findViewById(R.id.main_social_circle)).setChecked(true);
                        socialCirclePagerHolder.init();

                        break;
                    case 3:
                        currentPos = 3;
                        imagePersonal.setSelected(true);
                        ((RadioButton)findViewById(R.id.main_personal_center)).setChecked(true);
                        personalPagerHolder.init();

                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }

    void initHomeKeyListener(){

        mHomeKeyObserver = new HomeKeyObserver(this);
        mHomeKeyObserver.setHomeKeyListener(new HomeKeyObserver.OnHomeKeyListener() {
            @Override
            public void onHomeKeyPressed() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        viewPager.setCurrentItem(0);
                    }
                },500);

            }

            @Override
            public void onHomeKeyLongPressed() {
            }
        });
        mHomeKeyObserver.startListen();

    }


    class FragmentAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragmentList;

        public FragmentAdapter(FragmentManager fm,List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList = fragmentList;
        }

        @Override
        public Fragment getItem(int i) {


            return (fragmentList == null || fragmentList.size() == 0) ? null : fragmentList.get(i);
        }

        @Override
        public int getCount() {
            return fragmentList == null ? 0 : fragmentList.size();
        }



    }


    class onBottomListener implements View.OnClickListener {


        @Override
        public void onClick(View view) {

            imageImformation.setSelected(false);
            imageMessage.setSelected(false);
            imageSocial.setSelected(false);
            imagePersonal.setSelected(false);

            switch(view.getId()){

                case R.id.main_menu_layout_information:

                    viewPager.setCurrentItem(0);
                    currentPos = 0;
                    imageImformation.setSelected(true);
                    informationPagerHolder.init();

                    break;
                case R.id.main_menu_layout_message:
                    currentPos = 1;
                    viewPager.setCurrentItem(1);
                    imageMessage.setSelected(true);
                    chatHistoryFragment.init();

                    break;
                case R.id.main_menu_layout_social:
                    currentPos = 2;
                    viewPager.setCurrentItem(2);
                    imageSocial.setSelected(true);
                    socialCirclePagerHolder.init();

                    break;
                case R.id.main_menu_layout_personal:
                    currentPos = 3;
                    viewPager.setCurrentItem(3);
                    imagePersonal.setSelected(true);
                    personalPagerHolder.init();

                    break;

            }
        }
    }

    void initHuanXinAPI(){

        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);

        // 注册一个接收消息的BroadcastReceiver
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

        // 注册一个ack回执消息的BroadcastReceiver
        IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getAckMessageBroadcastAction());
        ackMessageIntentFilter.setPriority(3);
        registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

        //注册一个透传消息的BroadcastReceiver
        IntentFilter cmdMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getCmdMessageBroadcastAction());
        cmdMessageIntentFilter.setPriority(3);
        registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);

        EMContactManager.getInstance().setContactListener(new MyContactListener());
        // 注册一个监听连接状态的listener
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
        // 注册群聊相关的listener
        EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener());
        // 通知sdk，UI 已经初始化完毕，注册了相应的receiver和listener, 可以接受broadcast了
        EMChat.getInstance().setAppInited();



    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isConflict||!isCurrentAccountRemoved) {
            updateUnreadLabel();
            updateUnreadAddressLable();
            EMChatManager.getInstance().activityResumed();
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isConflict", isConflict);
        outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    void clear(){

        holder.clear();
        holder = null;

    }

    public void notiNewMessage(){

        pointMessage.setVisibility(View.VISIBLE);

    }


    public void hideNewMessage(){

        pointMessage.setVisibility(View.GONE);

    }


    public void notiNewSocial(){

        pointSocial.setVisibility(View.VISIBLE);

    }


    public void hideNewSocial(){

        pointSocial.setVisibility(View.GONE);

    }

    private void  startWebSocketService(){
        try{
            //开始服务
            Intent startIntent = new Intent(this, m_webscoketService.class);
            startService(startIntent);

            //与服务绑定
//			bindService(startIntent, connection, BIND_AUTO_CREATE);
        }catch (Exception e){
            Log.e("=====开启websocket服务失败=====",e.toString());
        }

    }

    /**
     * 检查当前用户是否被删除
     */
    public boolean getCurrentAccountRemoved(){
        return isCurrentAccountRemoved;
    }

    /**
     * 刷新未读消息数
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
//            unreadLabel.setText(String.valueOf(count));
//            unreadLabel.setVisibility(View.VISIBLE);

            notiNewMessage();

            Log.w("------未读信件-------------",String.valueOf(count));

        } else {
//            unreadLabel.setVisibility(View.INVISIBLE);
            hideNewMessage();
        }
    }

    /**
     * 获取未读消息数
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        return unreadMsgCountTotal;
    }

    /**
     * 新消息广播接收者
     *
     *
     */
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 主页面收到消息后，主要为了提示未读，实际消息内容需要到chat页面查看

            String from = intent.getStringExtra("from");
            // 消息id
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            // 2014-10-22 修复在某些机器上，在聊天页面对方发消息过来时不立即显示内容的bug
            if (ChatActivity1.activityInstance != null) {
                if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                    if (message.getTo().equals(ChatActivity1.activityInstance.getToChatUsername()))
                        return;
                } else {
                    if (from.equals(ChatActivity1.activityInstance.getToChatUsername()))
                        return;
                }
            }

            // 注销广播接收者，否则在ChatActivity中会收到这个广播
            abortBroadcast();

            notifyNewMessage(message);

            // 刷新bottom bar消息未读数
            updateUnreadLabel();


            // 当前页面如果为聊天历史页面，刷新此页面 通知刷新页面
                if (chatHistoryFragment != null) {
                    chatHistoryFragment.refresh();
            }

        }
    }

    /***
     * 好友变化listener
     *
     */
    private class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(List<String> usernameList) {
            // 保存增加的联系人
            Map<String, User> localUsers = SmartRobotApplication.getInstance().getContactList();
            Map<String, User> toAddUsers = new HashMap<String, User>();
            for (String username : usernameList) {
                User user = setUserHead(username);
                // 添加好友时可能会回调added方法两次
                if (!localUsers.containsKey(username)) {
                    userDao.saveContact(user);
                }
                toAddUsers.put(username, user);
            }
            localUsers.putAll(toAddUsers);

        }

        @Override
        public void onContactDeleted(final List<String> usernameList) {
            // 被删除
            Map<String, User> localUsers = SmartRobotApplication.getInstance().getContactList();
            for (String username : usernameList) {
                localUsers.remove(username);
                userDao.deleteContact(username);
                inviteMessgeDao.deleteMessage(username);
            }
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // 刷新ui
                     if(currentPos == 1)
                        chatHistoryFragment.refresh();
                }
            });

        }

        @Override
        public void onContactInvited(String username, String reason) {
            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();

            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null && inviteMessage.getFrom().equals(username)) {
                    inviteMessgeDao.deleteMessage(username);
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setReason(reason);
            Log.d(TAG, username + "请求加你为好友,reason: " + reason);
            // 设置相应status
            msg.setStatus(InviteMessage.InviteMesageStatus.BEINVITEED);
            notifyNewIviteMessage(msg);

        }

        @Override
        public void onContactAgreed(String username) {
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            Log.d(TAG, username + "同意了你的好友请求");
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAGREED);
            notifyNewIviteMessage(msg);

        }

        @Override
        public void onContactRefused(String username) {
            // 参考同意，被邀请实现此功能,demo未实现
            Log.d(username, username + "拒绝了你的好友请求");
        }

    }


    /**
     * 连接监听listener
     *
     */
    private class MyConnectionListener implements EMConnectionListener {

        @Override
        public void onConnected() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(chatHistoryFragment != null && chatHistoryFragment.errorItem != null)
                    chatHistoryFragment.errorItem.setVisibility(View.GONE);
                }

            });
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    if(error == EMError.USER_REMOVED){
                        // 显示帐号已经被移除
                        showAccountRemovedDialog();
                    }else if (error == EMError.CONNECTION_CONFLICT) {
                        // 显示帐号在其他设备登陆dialog
                        showConflictDialog();
                    } else {
                        if(chatHistoryFragment != null && chatHistoryFragment.errorItem != null){
                            chatHistoryFragment.errorItem.setVisibility(View.VISIBLE);
                            if (NetUtils.hasNetwork(MainActivity.this))
                                chatHistoryFragment.errorText.setText("连接不到聊天服务器");
                            else
                                chatHistoryFragment.errorText.setText("当前网络不可用，请检查网络设置");
                        }
                    }
                }

            });
        }
    }

    /**
     * 显示帐号在别处登录dialog
     */
    private void showConflictDialog() {

        Log.d("======================>","账号在其他地方登录");

        isConflictDialogShow = true;
        SmartRobotApplication.getInstance().logout(null);

        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                conflictBuilder.setTitle("下线通知");
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        conflictBuilder = null;
                        finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        //注销
                        HttpUtil.apiLogout();
                        com.smartrobot.smartrobot.util.User.getInstance().reSert();
                        com.smartrobot.smartrobot.util.User.saveUserInfo(getApplicationContext());
                        Util.stopWebsocketServer();
                    }
                });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
            }

        }

    }

    /**
     * 帐号被移除的dialog
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        SmartRobotApplication.getInstance().logout(null);

        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                accountRemovedBuilder.setTitle("移除通知");
                accountRemovedBuilder.setMessage(R.string.em_user_remove);
                accountRemovedBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        accountRemovedBuilder = null;
                        HttpUtil.apiLogout();
                        com.smartrobot.smartrobot.util.User.getInstance().reSert();
                        com.smartrobot.smartrobot.util.User.getInstance().saveUserInfo(getApplicationContext());
                        Util.stopWebsocketServer();
                        finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
                isCurrentAccountRemoved = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color userRemovedBuilder error" + e.getMessage());
            }

        }

    }

    /**
     * MyGroupChangeListener
     */
    private class MyGroupChangeListener implements GroupChangeListener {

        @Override
        public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {
            boolean hasGroup = false;
            for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(inviter + "邀请你加入了群聊"));
            // 保存邀请消息
            EMChatManager.getInstance().saveMessage(msg);
            // 提醒新消息
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // 刷新ui
                    if (currentPos == 1)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onInvitationAccpted(String groupId, String inviter, String reason) {

        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee, String reason) {

        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            // 提示用户被T了，demo省略此步骤
            // 刷新ui
            runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        updateUnreadLabel();
                        if (currentPos == 1)
                            chatHistoryFragment.refresh();
                        if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                            GroupsActivity.instance.onResume();
                        }
                    } catch (Exception e) {
                        EMLog.e(TAG, "refresh exception " + e.getMessage());
                    }

                }
            });
        }

        @Override
        public void onGroupDestroy(String groupId, String groupName) {
            // 群被解散
            // 提示用户群被解散,demo省略
            // 刷新ui
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    if (currentPos == 1)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) {
            // 用户申请加入群聊
            InviteMessage msg = new InviteMessage();
            msg.setFrom(applyer);
            msg.setTime(System.currentTimeMillis());
            msg.setGroupId(groupId);
            msg.setGroupName(groupName);
            msg.setReason(reason);
            Log.d(TAG, applyer + " 申请加入群聊：" + groupName);
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAPPLYED);
            notifyNewIviteMessage(msg);
        }

        @Override
        public void onApplicationAccept(String groupId, String groupName, String accepter) {
            // 加群申请被同意
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(accepter + "同意了你的群聊申请"));
            // 保存同意消息
            EMChatManager.getInstance().saveMessage(msg);
            // 提醒新消息
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // 刷新ui
                    if (currentPos == 1)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        @Override
        public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) {
            // 加群申请被拒绝，demo未实现
        }

    }


    /**
     * 保存提示新消息
     *
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        saveInviteMsg(msg);
        // 提示有新消息
        EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

        // 刷新bottom bar消息未读数
        updateUnreadAddressLable();

    }

    /**
     * 保存邀请等msg
     *
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // 保存msg
        inviteMessgeDao.saveMessage(msg);
        // 未读数加1
        User user = SmartRobotApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
        if (user.getUnreadMsgCount() == 0)
            user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
    }

    /**
     * 刷新申请与通知消息数
     */
    public void updateUnreadAddressLable() {
        runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadAddressCountTotal();
                if (count > 0) {
//                    unreadAddressLable.setText(String.valueOf(count));
//                    unreadAddressLable.setVisibility(View.VISIBLE);
                    Log.w("------环信申请数量-------",""+count);
                } else {
//                    unreadAddressLable.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    /**
     * 获取未读申请与通知消息
     *
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        if (SmartRobotApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME) != null)
            unreadAddressCountTotal = SmartRobotApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME).getUnreadMsgCount();
        return unreadAddressCountTotal;
    }

    /**
     * set head
     *
     * @param username
     * @return
     */
    User setUserHead(String username) {
        User user = new User();
        user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        return user;
    }

    /**
     * 消息回执BroadcastReceiver
     */
    private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();

            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");

            EMConversation conversation = EMChatManager.getInstance().getConversation(from);
            if (conversation != null) {
                // 把message设为已读
                EMMessage msg = conversation.getMessage(msgid);

                if (msg != null) {

                    // 2014-11-5 修复在某些机器上，在聊天页面对方发送已读回执时不立即显示已读的bug
                    if (ChatActivity1.activityInstance != null) {
                        if (msg.getChatType() == EMMessage.ChatType.Chat) {
                            if (from.equals(ChatActivity1.activityInstance.getToChatUsername()))
                                return;
                        }
                    }

                    msg.isAcked = true;
                }
            }

        }
    };



    /**
     * 透传消息BroadcastReceiver
     */
    private BroadcastReceiver cmdMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();
            EMLog.d(TAG, "收到透传消息");
            //获取cmd message对象
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = intent.getParcelableExtra("message");
            //获取消息body
            CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
            String action = cmdMsgBody.action;//获取自定义action

            //获取扩展属性 此处省略
//			message.getStringAttribute("");
            EMLog.d(TAG, String.format("透传消息：action:%s,message:%s", action,message.toString()));
        }
    };

    @Override
    protected void onDestroy() {

        mHomeKeyObserver.stopListen();
        super.onDestroy();
        // 注销广播接收者
        try {
            unregisterReceiver(msgReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(ackMessageReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(cmdMessageReceiver);
        } catch (Exception e) {
        }

        // try {
        // unregisterReceiver(offlineMessageReceiver);
        // } catch (Exception e) {
        // }

        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }

        //去除所有通知
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
        notificationManager.cancelAll();

    }

    void reLoginHuanXin(final String account,final String password){

        // 调用sdk登陆方法登陆聊天服务器
        EMChatManager.getInstance().login(account, password, new EMCallBack() {

            @Override
            public void onSuccess() {

                // 登陆成功，保存用户名密码
                SmartRobotApplication.getInstance().setUserName(account);
                SmartRobotApplication.getInstance().setPassword(password);
                try {
                    // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                    // ** manually load all local groups and
                    // conversations in case we are auto login
                    EMGroupManager.getInstance().loadAllGroups();
                    EMChatManager.getInstance().loadAllConversations();

                    List<String> usernames = EMContactManager.getInstance().getContactUserNames();
                    EMLog.d("roster", "contacts size: " + usernames.size());
                    Map<String,  User> userlist = new HashMap<String,  User>();
                    for (String username : usernames) {
                        User user = new User();
                        user.setUsername(username);
                        setUserHearder(username, user);
                        userlist.put(username, user);
                    }

                    // 存入内存
                    SmartRobotApplication.getInstance().setContactList(userlist);
                    // 存入db
                    UserDao dao = new UserDao(getApplicationContext());
                    List< User> users = new ArrayList< User>(userlist.values());
                    dao.saveContactList(users);

                    // 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
                    EMGroupManager.getInstance().getGroupsFromServer();
                } catch (Exception e) {
                    e.printStackTrace();
                    //取好友或者群聊失败，不让进入主页面，也可以不管这个exception继续进到主页面
                    runOnUiThread(new Runnable() {
                        public void run() {
                            SmartRobotApplication.getInstance().logout(null);
                        }
                    });
                    return;
                }
                //更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(SmartRobotApplication.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }
                // 进入主页面 出现这种情况是内存被杀死后，返回到主界面，由于跳过登录界面后所以需要在这里再登录一次


            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "登录失败: " + message, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }

    /**
     * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
     *
     * @param username
     * @param user
     */
    protected void setUserHearder(String username, User user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) { //成为后台程序
            moveTaskToBack(true);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    viewPager.setCurrentItem(0);
                }
            },100);
            return true;

        }

        return super.onKeyDown(keyCode, event);
    }

}
